package com.todo.pro.dt.queue.impl;

import com.todo.pro.dt.common.DtBase;
import com.todo.pro.dt.queue.DtQueue;

/**
 * Created by xuan on 2018/8/25.
 */
public class DefaultDtQueue extends DtBase implements DtQueue {

    private final static long LENGTH_NO_LIMIT = -1L;

    /**
     * 队列名称
     */
    private String name;
    /**
     * 队列长度
     */
    private long   maxLength;

    public DefaultDtQueue(String name, long maxLength) {
        this.name = name;
        this.maxLength = maxLength;
    }

    public DefaultDtQueue(String name) {
        this(name, LENGTH_NO_LIMIT);
    }

    @Override
    public boolean push(String... elements) {
        //如果用户限制了队列的长度，在push之前check队列是否满了
        if (LENGTH_NO_LIMIT != this.maxLength
            && (getClient().listLength(this.name) + elements.length) > this.maxLength) {
            return false;
        }
        getClient().listPushLeft(this.name, elements);
        return true;
    }

    @Override
    public String pop() {
        return getClient().listPopRight(this.name);
    }

    @Override
    public long length() {
        return getClient().listLength(this.name);
    }

}
